import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2coblpn/b2coblpnsubmitscreen.dart';
import 'package:opene/ui/b2ctrailer/b2ctrailermodel.dart';
import 'package:opene/ui/b2ctrailer/b2ctrailersubmitscreen.dart';
import 'package:opene/ui/fbamatch/fbamatchmodel.dart';
import 'package:opene/ui/fbamatch/fbamatchsearchscreen.dart';
import 'package:opene/ui/returns/newpreprocess/newpreprocessskuscreen.dart';
import 'package:opene/ui/returns/returnsdialogscreen.dart';
import 'package:opene/ui/returns/returnsmodel.dart';
import 'package:toast/toast.dart';

class NewPreprocessScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return NewPreprocessScreenPage();
  }
}

class NewPreprocessScreenPage extends StatefulWidget {
  @override
  _NewPreprocessPageState createState() => _NewPreprocessPageState();
}

class _NewPreprocessPageState extends BaseState<NewPreprocessScreen> {

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Returns:Tracking";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setRightIcon(Icons.not_interested);
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 0, top: 0, right: 0, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  preprocessV2ScanTrk(text, false);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        preprocessV2ScanTrk(text, false);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan fba label",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    "SKU/Barcode: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "QTY: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ],
              ),
              Expanded(
                child: Column(
                  children: [
                    Text(
                      newPreprocess == null ? "" : Utils.getStringisEmpty(newPreprocess.sku),
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      newPreprocess == null ? "" : Utils.getStringisInteger(newPreprocess.qty),
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  NewPreprocess newPreprocess;

  void preprocessV2ScanTrk(String trk, bool isSubmit) async {
    updateHint('');
    newPreprocess = null;
    Map<String, dynamic> map = new HashMap();
    map["trk"] = trk;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.preprocessV2ScanTrk, method: BaseMethod.post, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        newPreprocess = NewPreprocess.fromJson(baseResponse.data);
        if (newPreprocess == null) {
          newPreprocess = new NewPreprocess();
        }
        if (isSubmit) {

        }
      });
    } else if (baseResponse.status == 9106) {
      setState(() {
        newPreprocess = NewPreprocess.fromJson(baseResponse.data);
        if (newPreprocess == null) {
          newPreprocess = new NewPreprocess();
        }
        if (isSubmit) {

        }
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void preProcessCheckTrk(String trk) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["trk"] = trk;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.preProcessCheckTrk, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => NewPreprocessSkuScreen(newPreprocess: newPreprocess)),
      );
    } else if (baseResponse.status == 8013) {
      showDialog(
        context: context,
        builder: (context) => NewPreprocessDialog(processType:baseResponse.msg),
      ).then((value) =>
      {
        if ((value != null) && value )
          {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => NewPreprocessSkuScreen(newPreprocess: newPreprocess)),
            )
          }
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("scan tracking number barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (newPreprocess == null) {
      preprocessV2ScanTrk(textEditingController.text, true);
      return;
    }
    newPreprocess.trk = textEditingController.text;
    preProcessCheckTrk(textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
      newPreprocess = null;
    });
  }

  @override
  void setFeedBack() {
    // TODO: implement setFeedBack
    super.setFeedBack();
    preprocessV2NoTrk();
  }

  void preprocessV2NoTrk() async {
    updateHint('');
    newPreprocess = null;
    Map<String, dynamic> map = new HashMap();
    map["labelType"] = "PDF";

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.preprocessV2NoTrk, method: BaseMethod.post, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        NoTrkOrder noTrkOrder = NoTrkOrder.fromJson(baseResponse.data);
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}
